package com.zsj.comminlibrary.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.LruCache;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BgUtils {
    private LruCache<String, Bitmap> mCache;
    private static BgUtils sBgUtils;

    private BgUtils() {
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        int cacheSize = maxMemory / 8;
        mCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
            }
        };
    }

    public static BgUtils getInstance() {
        if (sBgUtils == null) {
            sBgUtils = new BgUtils();
        }
        return sBgUtils;
    }


    public Map<String,Bitmap> getBgBitmap() {
        try {
            String path = Environment.getExternalStorageDirectory() + "/smartPad/bg/";
            File file = new File(path);
            if (!file.exists()) {
                return null;
            }
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                return null;
            }
            List<File> bgFile = new ArrayList<>();
            for (File chileFile : files) {
                if (chileFile.isFile()) {
                    if (chileFile.getName().startsWith("bg_")) {
                        bgFile.add(chileFile);
                    }
                }
            }
            if (bgFile.size() == 0) {
                return null;
            }
            Map<String, Bitmap> map = new HashMap<>();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 4;
            for (File childFile : bgFile) {
                Bitmap bitmap = BitmapFactory.decodeFile(childFile.getPath(),options);
                mCache.put(childFile.getPath(), bitmap);
                map.put(childFile.getPath(), bitmap);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    public Bitmap getBitmap(String path) {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        Bitmap bitmap = mCache.get(path);
        if (bitmap != null) {
            return bitmap;
        }
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        Bitmap bitmap1 = BitmapFactory.decodeFile(path);
        if (bitmap1 == null) {
            return null;
        }
        mCache.put(path, bitmap1);
        return bitmap1;
    }
}
